package com.fs.chatx.module.common.service;

import com.fs.chatx.module.common.exception.MinioOperationException;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
@Slf4j
@Service
public class MinioService
{
    private final MinioClient minioClient;
    @Value("${minio.bucket-name}")
    private  String bucketName;

    public MinioService(MinioClient minioClient)
    {
        this.minioClient = minioClient;
    }
        /**
         * 上传文件到 MinIO
         */
        public String uploadFile(MultipartFile file) {

            try {
                String fileName = generateUniqueFileName(file.getOriginalFilename());
                log.info("正在上传文件：{}", fileName);
                ensureBucketExists();
                // 3. 执行上传
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName)
                                .object(fileName)
                                .stream(file.getInputStream(), file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                );
                String fileUrl=minioClient.getPresignedObjectUrl(
                        GetPresignedObjectUrlArgs.builder()
                                .method(Method.GET)
                                .bucket(bucketName)
                                .object(fileName)
                                .build()
                );
                log.info("文件上传成功，访问地址：{}", fileUrl);
                return fileUrl;
            } catch (Exception e) {
                log.error("文件上传失败", e);
                throw new MinioOperationException("文件上传失败", e);
            }
        }

        private String generateUniqueFileName(String originalFilename) {
        return UUID.randomUUID() + "_" + originalFilename;
    }

        private void ensureBucketExists()
        {
            try {
                log.info("bucket：{}", bucketName);
                if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                    log.info("存储桶 '{}' 不存在，正在创建...", bucketName);
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                }
            } catch (Exception e) {
                log.error("创建存储桶失败", e);
                throw new MinioOperationException("存储桶创建失败", e);
            }
        }


}
